package com.example.demo.controller;

import com.example.demo.ai.DeepSeekService;
import com.example.demo.ai.NewInterviewService;
import com.example.demo.ai.model.InterviewAnalysis;
import com.example.demo.ai.model.InterviewQA;
import com.example.demo.ai.model.ResumeAnalysis;
import com.example.demo.entity.Interview;
import com.example.demo.entity.InterviewQuestion;
import com.example.demo.entity.Resume;
import com.example.demo.entity.User;
import com.example.demo.service.InterviewService;
import com.example.demo.service.ResumeService;
import com.example.demo.service.UserService;
import com.example.demo.service.FileParserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/interview")
public class InterviewController {

    @Autowired
    private InterviewService interviewService;

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private UserService userService;

    @Autowired
    private DeepSeekService deepSeekService;
    
    @Autowired
    private NewInterviewService newInterviewService;
    
    @Autowired
    private FileParserService fileParserService;

    private static final Logger logger = LoggerFactory.getLogger(InterviewController.class);

    @GetMapping("/prepare")
    public String prepareInterview(Model model) {
        model.addAttribute("resume", new Resume());
        return "interview/prepare";
    }

    @PostMapping("/upload-resume")
    public String uploadResume(@RequestParam("file") MultipartFile file, 
                              @RequestParam("resumeText") String resumeText, 
                              @RequestParam("jobTitle") String jobTitle, 
                              @RequestParam(value = "jobDescription", required = false) String jobDescription, 
                              @RequestParam(value = "industry", required = false) String industry, 
                              @RequestParam(value = "difficulty", required = false, defaultValue = "2") Integer difficulty, 
                              Authentication authentication, Model model) {
        try {
            // 获取当前登录用户
            String username = authentication.getName();
            User user = userService.findByUsername(username);
            System.out.println("当前登录用户: " + username);

            // 验证必填字段
            if (jobTitle == null || jobTitle.trim().isEmpty()) {
                model.addAttribute("errorMessage", "请输入预期岗位");
                return "interview/prepare";
            }

            // 初始化简历内容变量
            String finalResumeText = resumeText;

            // 处理文件上传
            if (file != null && !file.isEmpty()) {
                System.out.println("收到文件上传请求，文件名: " + file.getOriginalFilename());
                
                // 先解析文件内容（在保存前）
                if (resumeText == null || resumeText.trim().isEmpty()) {
                    // 使用FileParserService解析文件内容
                    if (fileParserService.isSupportedFileType(file)) {
                        finalResumeText = fileParserService.parseFile(file);
                        // 如果解析结果为空，设置默认提示文本
                        if (finalResumeText == null || finalResumeText.trim().isEmpty()) {
                            finalResumeText = "简历文件: " + file.getOriginalFilename() + " (文件已上传，内容为空或解析失败)";
                        }
                    } else {
                        // 对于不支持的文件类型，设置提示文本
                        finalResumeText = "简历文件: " + file.getOriginalFilename() + " (不支持的文件类型，请上传PDF或DOCX格式)";
                    }
                }
                
                // 然后保存文件到磁盘
                // 检查上传目录是否存在
                File uploadDir = new File("C:/uploads/");
                if (!uploadDir.exists()) {
                    boolean created = uploadDir.mkdirs();
                    System.out.println("上传目录创建结果: " + created);
                }
                
                String filename = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
                String filePath = "C:/uploads/" + filename;
                try {
                    file.transferTo(new File(filePath));
                    
                    // 创建简历对象并设置文件信息
                    Resume resume = new Resume();
                    resume.setUserId(user.getId());
                    resume.setResumeText(finalResumeText);
                    resume.setFileName(filename);
                    resume.setFilePath(filePath);
                    
                    // 保存简历信息
                    boolean resumeSaved = resumeService.save(resume);
                    System.out.println("简历保存结果: " + resumeSaved);

                    if (!resumeSaved) {
                        model.addAttribute("errorMessage", "简历保存失败");
                        return "interview/prepare";
                    }

                    // 创建面试记录
                    Interview interview = new Interview();
                    interview.setUserId(user.getId());
                    interview.setResumeId(resume.getId());
                    interview.setJobTitle(jobTitle);
                    interview.setJobDescription(jobDescription);
                    interview.setIndustry(industry);
                    interview.setDifficulty(difficulty);
                    interview.setStatus(0); // 未开始
                    interview.setCreateTime(LocalDateTime.now());
                    interview.setUpdateTime(LocalDateTime.now());
                    
                    boolean interviewSaved = interviewService.save(interview);
                    System.out.println("面试记录保存结果: " + interviewSaved);

                    if (!interviewSaved) {
                        model.addAttribute("errorMessage", "面试创建失败");
                        return "interview/prepare";
                    }

                    return "redirect:/interview/start?interviewId=" + interview.getId();
                    
                } catch (IOException e) {
                    System.out.println("文件上传失败: " + e.getMessage());
                    model.addAttribute("errorMessage", "文件上传失败: " + e.getMessage());
                    return "interview/prepare";
                }
            }

            // 验证简历文本不能为空
            if (finalResumeText == null || finalResumeText.trim().isEmpty()) {
                model.addAttribute("errorMessage", "简历内容不能为空");
                return "interview/prepare";
            }

            Resume resume = new Resume();
            resume.setUserId(user.getId());
            resume.setResumeText(finalResumeText);

            // 保存简历信息
            boolean resumeSaved = resumeService.save(resume);
            System.out.println("简历保存结果: " + resumeSaved);

            if (!resumeSaved) {
                model.addAttribute("errorMessage", "简历保存失败");
                return "interview/prepare";
            }

            // 创建面试记录
            Interview interview = new Interview();
            interview.setUserId(user.getId());
            interview.setResumeId(resume.getId());
            interview.setJobTitle(jobTitle);
            interview.setJobDescription(jobDescription);
            interview.setIndustry(industry);
            interview.setDifficulty(difficulty);
            interview.setStatus(0); // 未开始
            interview.setCreateTime(LocalDateTime.now());
            interview.setUpdateTime(LocalDateTime.now());
            boolean interviewSaved = interviewService.save(interview);
            System.out.println("面试记录保存结果: " + interviewSaved);

            if (!interviewSaved) {
                model.addAttribute("errorMessage", "面试创建失败");
                return "interview/prepare";
            }

            model.addAttribute("interviewId", interview.getId());
            return "redirect:/interview/start?interviewId=" + interview.getId();
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("errorMessage", "操作失败: " + e.getMessage());
            return "interview/prepare";
        }
    }

    @GetMapping("/start")
    public String startInterview(@RequestParam("interviewId") Long interviewId, Model model) {
        try {
            logger.info("Starting interview with ID: {}", interviewId);
            
            Interview interview = interviewService.findById(interviewId);
            if (interview == null) {
                logger.error("Interview not found with ID: {}", interviewId);
                model.addAttribute("errorMessage", "面试不存在");
                return "error";
            }
            
            Resume resume = resumeService.findById(interview.getResumeId());
            if (resume == null) {
                logger.error("Resume not found for interview ID: {}", interviewId);
                model.addAttribute("errorMessage", "简历不存在");
                return "error";
            }

            // 生成面试问题
            List<String> questions = null;
            try {
                // 使用包含岗位信息的增强版方法
                questions = newInterviewService.generateInterviewQuestions(resume.getResumeText(), interview.getJobTitle(), interview.getJobDescription(), interview.getIndustry(), interview.getDifficulty(), 10);
                if (questions == null || questions.isEmpty()) {
                    logger.warn("No questions generated, using default questions");
                    // 使用默认问题
                    questions = Arrays.asList(
                            "请简单介绍一下你自己。",
                            "你为什么对这个职位感兴趣？",
                            "你最大的优势是什么？",
                            "你认为自己需要改进的地方是什么？",
                            "你对我们公司有什么了解？",
                            "请描述一次你解决复杂问题的经历。",
                            "你如何处理工作中的压力和挑战？",
                            "你有什么职业规划？",
                            "你如何与团队成员合作完成项目？",
                            "你为什么认为自己适合这个职位？"
                    );
                }
            } catch (Exception e) {
                logger.error("Error generating interview questions: {}", e.getMessage());
                // 使用默认问题
            questions = Arrays.asList(
                    "请简单介绍一下你自己。",
                    "你为什么对这个职位感兴趣？",
                    "你最大的优势是什么？",
                    "你认为自己需要改进的地方是什么？",
                    "你对我们公司有什么了解？",
                    "请描述一次你解决复杂问题的经历。",
                    "你如何处理工作中的压力和挑战？",
                    "你有什么职业规划？",
                    "你如何与团队成员合作完成项目？",
                    "你为什么认为自己适合这个职位？"
            );
            }
            
            // 分析简历内容
            ResumeAnalysis resumeAnalysis = null;
            try {
                // 使用包含岗位信息的增强版方法
                resumeAnalysis = newInterviewService.analyzeResume(resume.getResumeText(), interview.getJobTitle());
                if (resumeAnalysis == null) {
                    logger.warn("No resume analysis generated, using default analysis");
                    // 创建默认的简历分析结果
                    resumeAnalysis = new ResumeAnalysis();
                    resumeAnalysis.setScore(80.0);
                    resumeAnalysis.setSummary("您的简历基本符合要求，包含了必要的个人信息和工作经历。");
                    resumeAnalysis.setStrengths("简历结构清晰，工作经历连贯。");
                    resumeAnalysis.setAreasForImprovement("可以更突出个人成就和专业技能。");
                    resumeAnalysis.setSuggestions("1. 量化工作成果 2. 突出与目标职位相关的技能 3. 优化简历结构");
                    resumeAnalysis.setFormattingTips("使用清晰的标题层级，保持一致的格式，控制简历长度在1-2页。");
                }
            } catch (Exception e) {
                logger.error("Error analyzing resume: {}", e.getMessage());
                // 创建默认的简历分析结果
                resumeAnalysis = new ResumeAnalysis();
                resumeAnalysis.setScore(80.0);
                resumeAnalysis.setSummary("您的简历基本符合要求，包含了必要的个人信息和工作经历。");
                resumeAnalysis.setStrengths("简历结构清晰，工作经历连贯。");
                resumeAnalysis.setAreasForImprovement("可以更突出个人成就和专业技能。");
                resumeAnalysis.setSuggestions("1. 量化工作成果 2. 突出与目标职位相关的技能 3. 优化简历结构");
                resumeAnalysis.setFormattingTips("使用清晰的标题层级，保持一致的格式，控制简历长度在1-2页。");
            }

            // 保存面试问题
            for (int i = 0; i < questions.size(); i++) {
                InterviewQuestion question = new InterviewQuestion();
                question.setInterviewId(interviewId);
                question.setQuestion(questions.get(i));
                question.setOrderNumber(i + 1);
                interviewService.saveQuestion(question);
            }

            // 更新面试状态为进行中
            interview.setStatus(1);
            interviewService.update(interview);

            model.addAttribute("interviewId", interviewId);
            model.addAttribute("questions", questions);
            model.addAttribute("resumeAnalysis", resumeAnalysis);
            
            logger.info("Successfully prepared interview with ID: {}", interviewId);
            return "interview/chat";
        } catch (Exception e) {
            logger.error("Error starting interview: {}", e.getMessage());
            model.addAttribute("errorMessage", "启动面试时发生错误：" + e.getMessage());
            return "error";
        }
    }

    @PostMapping("/submit-answers")
    public String submitAnswers(@RequestParam("interviewId") Long interviewId, @RequestParam Map<String, String> answers, Model model) {
        try {
            Interview interview = interviewService.findById(interviewId);
            Resume resume = resumeService.findById(interview.getResumeId());
            List<InterviewQuestion> questions = interviewService.findQuestionsByInterviewId(interviewId);

            // 更新问题的回答
            List<InterviewQA> qaList = new ArrayList<>();
            for (int i = 0; i < questions.size(); i++) {
                InterviewQuestion question = questions.get(i);
                // 尝试通过索引获取答案（前端模板使用的方式）
                String answer = answers.get("answer_" + i);
                
                // 如果没找到，尝试通过ID获取答案（兼容旧的方式）
                if (answer == null) {
                    answer = answers.get("answer_" + question.getId());
                }
                
                question.setUserAnswer(answer);
                interviewService.saveQuestion(question);

                InterviewQA qa = new InterviewQA();
                qa.setQuestion(question.getQuestion());
                qa.setAnswer(answer);
                qaList.add(qa);
            }

            // 分析面试答案
            InterviewAnalysis analysis = newInterviewService.analyzeInterviewAnswers(resume.getResumeText(), qaList, interview.getJobTitle());

            // 更新面试结果
            interview.setStatus(2); // 已完成
            interview.setOverallScore(analysis.getScore());
            interview.setSummary(analysis.getSuggestion());
            interviewService.update(interview);

            // 生成示例答案
            List<InterviewQA> exampleQAs = new ArrayList<>();
            try {
                // 尝试使用AI生成示例答案
                exampleQAs = newInterviewService.generateExampleAnswers(resume.getResumeText(), qaList, interview.getJobTitle());
            } catch (Exception e) {
                logger.warn("Failed to generate example answers using AI: {}", e.getMessage());
                // 如果AI生成失败，使用默认的示例答案
                for (InterviewQA qa : qaList) {
                    InterviewQA exampleQA = new InterviewQA();
                    exampleQA.setQuestion(qa.getQuestion());
                    // 根据问题类型提供不同的示例答案
                    if (qa.getQuestion().contains("介绍自己")) {
                        exampleQA.setAnswer("我是一名经验丰富的软件工程师，拥有X年的相关工作经验。我熟悉Java、Spring框架等技术栈，曾参与多个大型项目的开发。我注重团队合作，善于解决复杂问题，并且持续学习新技术以提升自己的专业能力。");
                    } else if (qa.getQuestion().contains("优势")) {
                        exampleQA.setAnswer("我最大的优势是我的技术能力和解决问题的能力。我能够快速理解业务需求并转化为技术方案，同时在项目中遇到挑战时能够保持冷静并找到有效的解决方案。此外，我还具有良好的团队协作精神，能够与不同背景的同事有效沟通和合作。");
                    } else if (qa.getQuestion().contains("改进")) {
                        exampleQA.setAnswer("我认为我在时间管理方面还有提升空间。有时为了追求完美，我会在某些细节上花费过多时间，导致项目进度受到影响。为了改进这一点，我正在学习使用敏捷开发方法和项目管理工具，以更好地平衡质量和效率。");
                    } else {
                        exampleQA.setAnswer("这是一个很好的问题。根据我的经验和理解，我认为最佳的做法是...");
                    }
                    exampleQAs.add(exampleQA);
                }
            }

            model.addAttribute("interview", interview);
            model.addAttribute("questions", questions);
            model.addAttribute("analysis", analysis);
            model.addAttribute("qas", qaList);
            model.addAttribute("exampleQAs", exampleQAs);
            return "interview/result";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("errorMessage", "提交回答失败");
            model.addAttribute("interviewId", interviewId);
            return "redirect:/interview/start?interviewId=" + interviewId;
        }
    }

    @GetMapping("/history")
    public String interviewHistory(Authentication authentication, Model model) {
        // 获取当前登录用户的所有面试记录
        String username = authentication.getName();
        User user = userService.findByUsername(username);
        List<Interview> interviews = interviewService.findByUserId(user.getId());
        
        // 按创建时间倒序排序
        interviews.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));
        
        // 计算统计数据
        if (!interviews.isEmpty()) {
            // 计算平均评分
            double avgScore = interviews.stream()
                .filter(interview -> interview.getOverallScore() != null)
                .mapToDouble(Interview::getOverallScore)
                .average()
                .orElse(0.0);
            
            // 获取最高评分
            double highestScore = interviews.stream()
                .filter(interview -> interview.getOverallScore() != null)
                .mapToDouble(Interview::getOverallScore)
                .max()
                .orElse(0.0);
            
            // 获取最近面试日期
            String lastInterviewDate = interviews.stream()
                .max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime()))
                .map(interview -> interview.getCreateTime().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                .orElse("");
            
            model.addAttribute("avgScore", avgScore);
            model.addAttribute("highestScore", highestScore);
            model.addAttribute("lastInterviewDate", lastInterviewDate);
        }
        
        model.addAttribute("interviews", interviews);
        return "interview/history";
    }

    @GetMapping("/detail")
    public String interviewDetail(@RequestParam("interviewId") Long interviewId, Model model) {
        Interview interview = interviewService.findById(interviewId);
        List<InterviewQuestion> questions = interviewService.findQuestionsByInterviewId(interviewId);
        model.addAttribute("interview", interview);
        model.addAttribute("questions", questions);
        return "interview/detail";
    }

    @PostMapping("/generate-next-question")
    @ResponseBody
    public ResponseEntity<?> generateNextQuestion(@RequestParam Long interviewId, @RequestParam Integer currentQuestionIndex) {
        try {
            // 查询面试信息
            Interview interview = interviewService.findById(interviewId);
            if (interview == null) {
                return ResponseEntity.badRequest().body("面试不存在");
            }
            
            // 查询当前面试已有的问题
            List<InterviewQuestion> existingQuestions = interviewService.findQuestionsByInterviewId(interviewId);
            List<String> previousQuestions = existingQuestions.stream()
                .map(InterviewQuestion::getQuestion)
                .collect(Collectors.toList());
            
            // 获取简历信息
            Resume resume = resumeService.findById(interview.getResumeId());
            if (resume == null) {
                return ResponseEntity.badRequest().body("简历不存在");
            }
            
            // 检查是否已达到最大问题数（10个）
            if (existingQuestions.size() >= 10) {
                return ResponseEntity.badRequest().body("已达到最大问题数量限制（10个）");
            }
            
            // 检查当前问题是否已回答
            if (currentQuestionIndex != null && currentQuestionIndex >= 0 && currentQuestionIndex < existingQuestions.size()) {
                InterviewQuestion currentQuestion = existingQuestions.get(currentQuestionIndex);
                if (currentQuestion.getUserAnswer() == null || currentQuestion.getUserAnswer().trim().isEmpty()) {
                    return ResponseEntity.badRequest().body("请先回答当前问题");
                }
            }
            
            // 确定下一个问题的序号
            int nextQuestionOrder = existingQuestions.size() + 1;
            
            // 生成新问题
            String newQuestion;
            
            // 检查是否有用户回答，如果有，则使用结合用户回答的方法生成问题
            boolean hasUserAnswers = existingQuestions.stream()
                .anyMatch(q -> q.getUserAnswer() != null && !q.getUserAnswer().trim().isEmpty());
            
            if (hasUserAnswers) {
                // 转换为InterviewQA列表
                List<InterviewQA> qaList = existingQuestions.stream()
                    .filter(q -> q.getUserAnswer() != null && !q.getUserAnswer().trim().isEmpty())
                    .map(q -> {
                        InterviewQA qa = new InterviewQA();
                        qa.setQuestion(q.getQuestion());
                        qa.setAnswer(q.getUserAnswer());
                        return qa;
                    })
                    .collect(Collectors.toList());
                
                // 使用新的结合用户回答的方法生成问题
                newQuestion = newInterviewService.generateSingleQuestionWithContext(
                    resume.getResumeText(),
                    interview.getJobTitle(),
                    interview.getJobDescription(),
                    interview.getIndustry(),
                    interview.getDifficulty(),
                    qaList
                );
            } else {
                // 如果没有用户回答，使用原来的方法生成问题
                newQuestion = deepSeekService.generateSingleInterviewQuestion(
                    resume.getResumeText(),
                    interview.getJobTitle(),
                    interview.getJobDescription(),
                    interview.getIndustry(),
                    interview.getDifficulty(),
                    previousQuestions
                );
            }
            
            // 保存新问题
            InterviewQuestion question = new InterviewQuestion();
            question.setInterviewId(interviewId);
            question.setQuestion(newQuestion);
            question.setOrderNumber(nextQuestionOrder);
            interviewService.saveQuestion(question);
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("question", newQuestion);
            result.put("questionIndex", nextQuestionOrder - 1); // 前端从0开始
            result.put("totalQuestions", nextQuestionOrder); // 当前总问题数
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("生成下一个问题失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("生成问题失败: " + e.getMessage());
        }
    }

    @PostMapping("/save-answer")
    @ResponseBody
    public ResponseEntity<?> saveAnswer(@RequestParam Long interviewId, @RequestParam Integer questionIndex, @RequestBody String answer) {
        try {
            // 查询面试信息
            Interview interview = interviewService.findById(interviewId);
            if (interview == null) {
                return ResponseEntity.badRequest().body("面试不存在");
            }
            
            // 查询对应序号的问题
            List<InterviewQuestion> questions = interviewService.findQuestionsByInterviewId(interviewId);
            if (questionIndex < 0 || questionIndex >= questions.size()) {
                return ResponseEntity.badRequest().body("问题索引无效");
            }
            
            // 更新答案
            InterviewQuestion question = questions.get(questionIndex);
            question.setUserAnswer(answer);
            interviewService.saveQuestion(question);
            
            return ResponseEntity.ok("答案保存成功");
        } catch (Exception e) {
            logger.error("保存答案失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("保存答案失败: " + e.getMessage());
        }
    }
}